<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="SIM卡卡号"
        v-model="queryForm.iccid"
      ></el-input>
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="移动手机号码"
        v-model="queryForm.phone"
      ></el-input>
      <el-select
        clearable
        style="width: 170px"
        class="filter-item"
        v-model="queryForm.type"
        placeholder="请选择SIM卡类型"
      >
        <el-option
          v-for="(val, key) in Dicts.COMMUNICATION_TYPE"
          :key="key"
          :label="val"
          :value="key"
        ></el-option>
      </el-select>
      <el-select
        clearable
        style="width: 170px"
        class="filter-item"
        v-model="queryForm.status"
        placeholder="请选择注册状态"
      >
        <el-option
          v-for="(val, key) in Dicts.SIM_STATUS"
          :key="key"
          :label="val"
          :value="key"
        ></el-option>
      </el-select>
      <el-button
        class="filter-item"
        @click="doQuery"
        type="primary"
        icon="el-icon-search"
        >查询</el-button
      >
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        @click="addSim"
        type="success"
        icon="el-icon-plus"
        v-permission="'sim:add'"
        >新增</el-button
      >
    </div>
    <el-table v-loading="loading" :data="records" style="width: 100%">
      <el-table-column prop="rowId" label="ID" width="100" align="center">
      </el-table-column>
      <el-table-column
        prop="iccid"
        label="SIM卡卡号"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="phone"
        label="移动手机号码"
        width="200"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="type"
        label="SIM卡所属类型"
        width="250"
        align="center"
      >
        <template slot-scope="scope">
          {{ Dicts.COMMUNICATION_TYPE[scope.row.type] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="绑定状态"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          {{ Dicts.SIM_STATUS[scope.row.status] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="usedFlow"
        label="使用流量：单位/M"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="leftFlow"
        label="剩余流量：单位/M"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="productName"
        label="办理业务"
        width="300"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="更新时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding"
        fixed="right"
        width="150"
      >
        <template slot-scope="scope">
          <!-- <el-button type="success"
                     size="mini"
                     v-if="scope.row.status !== 1"
                     @click="bindingSimChack(scope.row.rowId, scope.row.phone)"
                     title="绑定"
                     icon="el-icon-check"
                     v-permission="'sim:bindingSim'"
                     circle></el-button> -->
          <el-button
            v-permission="'sim:detail'"
            size="mini"
            type="primary"
            @click="handleOpenMonitor(scope.row.rowId)"
            title="sim卡详情"
            icon="el-icon-view"
            circle
          ></el-button>
          <!-- <el-button type="danger" size="mini" v-else @click="untieSimChack(scope.row.rowId, scope.row.phone)" title="解绑" icon="el-icon-close" v-permission="'sim:unbindSim'" circle></el-button> -->
          <!-- <el-button type="primary" size="mini" v-if="scope.row.status === 0" @click="editSimForm(scope.row.rowId)" title="编辑" icon="el-icon-edit" circle></el-button> -->
          <!-- <el-button size="mini" type="danger" v-if="scope.row.status === 0" @click="handleDelete(scope.row.rowId)"  title="删除" icon="el-icon-delete" circle ></el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryForm.total"
      >
      </el-pagination>
    </div>

    <!-- 修改新增弹框 -->
    <el-dialog
      :title="`${editForm.rowId ? '编辑' : '新增'}通信卡`"
      :visible.sync="dialogFormVisible"
      width="30%"
    >
      <el-form
        :model="editForm"
        label-width="140px"
        :rules="editFormRules"
        ref="editForm"
      >
        <el-form-item label="SIM卡卡号:" prop="iccid">
          <el-input v-model="editForm.iccid" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="移动手机号码:" prop="phone">
          <el-input v-model="editForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="SIM卡所属类型:" prop="type">
          <el-select
            v-model="editForm.type"
            placeholder="SIM卡所属类型"
            style="width: 100%;"
          >
            <el-option
              v-for="(val, key) in Dicts.COMMUNICATION_TYPE"
              :key="key"
              :label="val"
              :value="key"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述:" prop="remark">
          <el-input
            v-model="editForm.remark"
            type="textarea"
            auto-complete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSim(editForm.rowId)"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="sim卡详情"
      :visible.sync="dialogCurveVisible"
      :append-to-body="true"
      width="50%"
    >
      <el-form ref="sizeForm" :model="sizeForm" label-width="80px" size="mini">
        <el-form-item>
          <el-row
            class="panel-group"
            :gutter="10"
            type="flex"
            justify="center"
            style="margin-left: -80px;"
          >
            <el-col :span="6" class="card-panel-col">
              <div class="card-panel">
                <div class="card-panel-icon-wrapper icon-people">
                  <svg-icon icon-class="peoples" class-name="card-panel-icon" />
                </div>
                <div class="card-panel-description">
                  <div class="card-panel-text">已使用流量(M)</div>
                  <div class="card-panel-num">{{ SimInfo.usedFlow }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6" class="card-panel-col">
              <div class="card-panel">
                <div class="card-panel-icon-wrapper icon-message">
                  <svg-icon icon-class="excel" class-name="card-panel-icon" />
                </div>
                <div class="card-panel-description">
                  <div class="card-panel-text">剩余流量(M)</div>
                  <div class="card-panel-num">{{ SimInfo.leftFlow }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6" class="card-panel-col">
              <div class="card-panel">
                <div class="card-panel-icon-wrapper icon-money">
                  <svg-icon icon-class="wechat" class-name="card-panel-icon" />
                </div>
                <div class="card-panel-description">
                  <div class="card-panel-text">绑定设备号</div>
                  <div class="card-panel-num">{{ SimInfo.deviceCode }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6" class="card-panel-col">
              <div class="card-panel">
                <div class="card-panel-icon-wrapper icon-shoppingCard">
                  <svg-icon icon-class="bug" class-name="card-panel-icon" />
                </div>
                <div class="card-panel-description">
                  <div class="card-panel-text">所属企业</div>
                  <div class="card-panel-num">{{ SimInfo.bussinessName }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-col :span="12" style="padding-left:-10px;">
            <el-date-picker
              type="daterange"
              start-placeholder="开始日期"
              range-separator="至"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              v-model="sizeForm.pickerDate"
              @change="dateChangebirthday1"
              :picker-options="pickerOptions0"
              style="width: 420px;height:30px;align:center;font-size:20px;"
            ></el-date-picker>
          </el-col>
          <el-col :span="4" style="padding-left:15px;">
            <button class="button_name" @click="onSubmite">查询</button>
          </el-col>
        </el-form-item>
      </el-form>
      <div
        id="myChart"
        style="width:850px ;height:400px;left:25px;padding-top:30px;"
      ></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeDialog">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  querySim,
  deleteSim,
  addOrEditSim,
  detailSim,
  bindingSim,
  untieSim,
  SimHistory,
  SimInfo
} from '@/api/communication'
import echarts from 'echarts'
require('echarts/theme/macarons')
export default {
  name: 'sim',
  data() {
    return {
      loading: false,
      dialogFormVisible: false,
      queryForm: {
        current: 1,
        pages: 0,
        total: 0,
        size: 10,
        logType: undefined,
        title: undefined
      },
      editForm: {
        rowId: 0,
        iccid: '',
        phone: '',
        remark: '',
        type: ''
      },
      editFormRules: {
        iccid: [{ required: true, message: '请填写SIM号码', trigger: 'blur' }],
        phone: [{ required: true, message: '请填写手机号码', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        remark: [{ required: true, message: '请填写描述', trigger: 'blur' }]
      },
      records: [],
      sizeForm: {
        pickerDate: [],
        params: {}
      },
      SimInfo: {
        usedFlow: 1024,
        leftFlow: 512,
        deviceCode: 1581195993254,
        bussinessName: '海博集团'
      },
      dataCurve: {
        echatX: [
          '2019-10-27',
          '2019-10-28',
          '2019-10-29',
          '2019-10-30',
          '2019-10-31',
          '2019-11-1',
          '2019-11-2'
        ],
        usedFlow: [0, 0, 0, 0, 0, 0, 0]
      },
      dialogCurveVisible: false,
      rowIdForm: {},
      pickerOptions0: {
        disabledDate(time) {
          // 配合:picker-options  > 表示禁选当前天之后。< 表示禁选当前天之前- 8.64e6
          return time.getTime() > Date.now()
        }
      }
    }
  },
  created() {
    this.doQuery()
  },
  watch: {
    // 监听dataCurve对象的变化
    dataCurve: {
      deep: true,
      handler: function(newVal) {
        // console.log('渲染图表数据', newVal)
        // 重新渲染折线图
        this.$nextTick(() => this.initchart())
      }
    }
  },
  methods: {
    handleCurrentChange(current) {
      this.queryForm.current = current
      this.doQuery()
    },
    handleSizeChange(size) {
      this.queryForm.size = size
      this.doQuery()
    },
    doQuery() {
      this.loading = true
      querySim(this.queryForm).then(({ data: { data } }) => {
        // console.log(data)
        this.queryForm.current = data.current
        this.queryForm.pages = data.pages
        this.queryForm.total = data.total
        this.queryForm.size = data.size
        this.records = data.records
        this.loading = false
      })
    },
    handleOpenMonitor(rowId) {
      // 打开弹窗
      this.dialogCurveVisible = true
      // 拿到设备编号deviceCode
      this.rowIdForm.rowId = rowId
      // console.log('第一次传参', this.rowIdForm.rowId)
      SimInfo(this.rowIdForm).then(({ data: { data } }) => {
        var data_1 = data
        // console.log('第一次请求的数据', data_1)
        this.SimInfo.usedFlow = data_1.usedFlow
        this.SimInfo.leftFlow = data_1.leftFlow
        this.SimInfo.deviceCode = data_1.deviceCode
        this.SimInfo.bussinessName = data_1.bussinessName
      })
      // 初始化折线
      this.$nextTick(() => this.initchart())
    },
    dateChangebirthday1(val) {
      // 获取日期选择器选择的值
      var data2 = val
      // 当获取到后台的数据后，如果不为空或空字符串，就赋值。
      if (data2 !== null) {
        if (data2.property !== null) {
          this.sizeForm.params.simId = this.rowIdForm.rowId
          this.sizeForm.params.start = data2[0]
          this.sizeForm.params.end = data2[1]
          // console.log('第二次传参', this.sizeForm.params)
        }
      }
    },
    onSubmite() {
      if (this.sizeForm !== null) {
        if (this.sizeForm.property !== null) {
          SimHistory(this.sizeForm.params).then(({ data: { data } }) => {
            // console.log('第二次请求到的数据', data)
            if (data !== null) {
              if (data.property !== null) {
                var d_arr = data
                var d_arr_init = []
                for (var k in d_arr) {
                  var d = new Date(parseInt(k))
                  var d_init =
                    d.getFullYear() +
                    '-' +
                    (d.getMonth() + 1) +
                    '-' +
                    d.getDate()
                  d_arr_init.push(d_init)
                }
                this.dataCurve.usedFlow = Object.values(data)
                this.dataCurve.echatX = d_arr_init
              }
            }
          })
        }
      }
      // 请求数据
    },
    // 关闭弹框的事件
    closeDialog() {
      this.dialogCurveVisible = false
      this.dataCurve = {
        echatX: [
          '2019-10-27',
          '2019-10-28',
          '2019-10-29',
          '2019-10-30',
          '2019-10-31',
          '2019-11-1',
          '2019-11-2'
        ],
        usedFlow: [0, 0, 0, 0, 0, 0, 0]
      }
      this.SimInfo = {
        usedFlow: 1024,
        leftFlow: 512,
        phone: 1581195993254,
        bussinessName: '海博集团'
      }
      this.sizeForm = {}
    },
    handleDelete(rowId) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSim(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    addSim() {
      this.editForm = {}
      this.dialogFormVisible = true
    },
    saveSim(rowId) {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          addOrEditSim(this.editForm).then(({ data: { data, msg, code } }) => {
            if (code === 0) {
              this.doQuery()
              this.dialogFormVisible = false
            }
            this.$message({
              showClose: true,
              message: msg,
              type: code === 0 ? 'success' : 'error'
            })
          })
        } else {
          return false
        }
      })
    },
    editSimForm(rowId) {
      detailSim(rowId).then(({ data: { code, data, msg } }) => {
        this.addSim()
        this.editForm = {
          rowId: data.rowId,
          iccid: data.iccid,
          phone: data.phone,
          type: data.type.toString(),
          remark: data.remark
        }
      })
    },
    bindingSimChack(rowId, phone) {
      bindingSim(rowId, phone).then(({ data: { data, msg } }) => {
        this.doQuery()
        this.$message({
          showClose: true,
          message: msg,
          type: 'success'
        })
      })
    },
    untieSimChack(rowId, phone) {
      this.$confirm('此操作将解绑通信卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        untieSim(rowId, phone).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    initchart() {
      const myChart = echarts.init(document.getElementById('myChart'))
      myChart.setOption(
        {
          title: {
            left: 'left',
            show: false
          },
          grid: {
            x: 65,
            y: 45,
            x2: 75,
            y2: 45
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['usedFlow']
          },
          toolbox: {
            show: true,
            right: 30, // 是否显示工具栏组件
            itemSize: 20, // 工具栏 icon 的大小
            showTitle: true, // 是否在鼠标 hover 的时候显示每个工具 icon 的标题
            feature: {
              mark: {
                // '辅助线开关'
                show: true
              },
              dataView: {
                show: true,
                title: '数据视图',
                readOnly: true,
                lang: ['数据视图', '关闭'],
                optionToContent: function(opt) {
                  var axisData = opt.xAxis[0].data
                  var series = opt.series
                  var tdHeads = '<td  style="padding:0 10px">名称</td>'
                  series.forEach(function(item) {
                    tdHeads +=
                      '<td style="padding: 3px 10px">' + item.name + '</td>'
                  })
                  var table =
                    '<table border="1" style="margin-left:20px;border-collapse:collapse;font-size:18px;text-align:center"><tbody><tr>' +
                    tdHeads +
                    '</tr>'
                  var tdBodys = ''
                  for (var i = 0, l = axisData.length; i < l; i++) {
                    for (var j = 0; j < series.length; j++) {
                      if (typeof series[j].data[i] === 'object') {
                        tdBodys += '<td>' + series[j].data[i].value + '</td>'
                      } else {
                        tdBodys += '<td>' + series[j].data[i] + '</td>'
                      }
                    }
                    table +=
                      '<tr><td style="padding: 3px 10px">' +
                      axisData[i] +
                      '</td>' +
                      tdBodys +
                      '</tr>'
                    tdBodys = ''
                  }
                  table += '</tbody></table>'
                  return table
                }
              },
              magicType: {
                // 动态类型切换
                show: true,
                title: '切换', // 各个类型的标题文本，可以分别配置。
                type: ['bar', 'line'] // 启用的动态类型，包括'line'（切换为折线图）, 'bar'（切换为柱状图）, 'stack'（切换为堆叠模式）, 'tiled'（切换为平铺模式）
              },
              restore: {
                // 配置项还原。
                show: true, // 是否显示该工具。
                title: '还原'
              },
              saveAsImage: {
                // 保存为图片。
                show: true, // 是否显示该工具。
                type: 'png', // 保存的图片格式。支持 'png' 和 'jpeg'。
                name: 'pic1', // 保存的文件名称，默认使用 title.text 作为名称
                backgroundColor: '#ffffff', // 保存的图片背景色，默认使用 backgroundColor，如果
                title: '保存为图片',
                pixelRatio: 1 // 保存图片的分辨率比例，默认跟容器相同大小，如果需要保存更高分辨率的，可以设置为大于 1 的值，例如 2
              }
            }
          },
          xAxis: {
            type: 'category',
            splitLine: { show: false },
            name: '日期',
            data: this.dataCurve.echatX,
            axisPointer: {
              type: 'line'
            },
            axisLabel: {
              rotate: 8
            }
          },
          // 设置两个y轴，左边显示数量，右边显示概率
          yAxis: [
            {
              splitLine: { show: false },
              type: 'value',
              name: 'usedFlow'
              // show: true,
              // max: 5000,
              // min: 0,
              // interval: 1000
            }
          ],
          // 每个设备分数量、概率2个指标，只要让他们的name一致，即可通过，legeng进行统一的切换
          series: [
            {
              name: 'usedFlow',
              type: 'line',
              symbol: 'circle', // 折线点设置为实心点
              symbolSize: 5, // 折线点的大小
              data: this.dataCurve.usedFlow,
              barWidth: 30,
              itemStyle: {
                normal: {
                  color: '#b6a2de',
                  lineStyle: {
                    color: '#b6a2de'
                  }
                }
              },
              areaStyle: {
                normal: {
                  // 颜色渐变函数 前四个参数分别表示四个位置依次为左、下、右、上
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: 'rgba(46,199,201,0.5)'
                    },
                    {
                      offset: 0.4,
                      color: 'rgba(56,155,255,0.25)'
                    },
                    {
                      offset: 1,
                      color: 'rgba(38,197,254,0.03)'
                    }
                  ])
                }
              } // 区域颜色渐变
            }
          ]
        },
        true
      )
    }
  },
  components: {}
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.button_name {
  width: 80px;
  height: 30px;
  background-color: #67c23a;
  font-size: 15px;
  border-radius: 4px;
  color: white;
  border: none;
  outline: none;
  text-align: center;
  text-decoration: none;
  display: inline-block;
}
.button_name {
  -webkit-transition-duration: 0.2s; /* Safari */
  transition-duration: 0.2s;
}
.button_name:hover {
  background-color: #85ce61; /* Green */
  color: white;
}

.panel-group {
  margin-top: 4px;
  .card-panel-col {
    margin-bottom: 10px;
  }
  .card-panel {
    height: 80px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    padding-left: 0px;
    padding-right: 10px;
    color: #666;
    background: rgb(240, 240, 240);
    box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
    border-color: rgba(0, 0, 0, 0.1);
    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }
      .icon-people {
        background: #40c9c6;
      }
      .icon-message {
        background: #36a3f7;
      }
      .icon-money {
        background: #f4516c;
      }
      .icon-shoppingCard {
        background: #34bfa3;
      }
    }
    .icon-people {
      color: #40c9c6;
    }
    .icon-message {
      color: #36a3f7;
    }
    .icon-money {
      color: #f4516c;
    }
    .icon-shoppingCard {
      color: #34bfa3;
    }
    .card-panel-icon-wrapper {
      float: left;
      margin: 10px 0 0 14px;
      padding: 14px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }
    .card-panel-icon {
      float: left;
      font-size: 30px;
    }
    .card-panel-description {
      float: left;
      font-weight: bold;
      margin: 15px 0px 14px 10px;
      .card-panel-text {
        line-height: 16px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }
      .card-panel-num {
        font-size: 18px;
      }
    }
  }
}
</style>
